<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import Sidebar from './components/Sidebar.vue'
import NoteEditor from './components/NoteEditor.vue'
import Toolbar from './components/Toolbar.vue'

interface Note {
  id: number
  title: string
  content: string
  createdAt: Date
  updatedAt: Date
}

// 当前选中的笔记
const currentNote = ref<Note | null>(null)
// 笔记列表
const notes = ref<Note[]>([])
// 是否为脱出窗口模式
const isDetachedMode = ref(false)
// 脱出窗口置顶功能
const isDetachedWindowAlwaysOnTop = ref(false)

// 选择笔记
const selectNote = (note: Note): void => {
  currentNote.value = note
}

// 创建新笔记
const createNote = (): void => {
  const newNote: Note = {
    id: Date.now(),
    title: '新笔记',
    content: '',
    createdAt: new Date(),
    updatedAt: new Date()
  }
  notes.value.unshift(newNote)
  currentNote.value = newNote
}

// 更新笔记
const updateNote = async (content: string): Promise<void> => {
  if (currentNote.value) {
    currentNote.value.content = content
    currentNote.value.updatedAt = new Date()
    // 根据内容生成标题
    const lines = content.split('\n')
    const firstLine = lines[0]?.trim()
    if (firstLine) {
      currentNote.value.title =
        firstLine.length > 30 ? firstLine.substring(0, 30) + '...' : firstLine
    }

    // 如果是脱出窗口模式，更新主进程中的note数据
    if (isDetachedMode.value && window.api && window.api.updateDetachedNote) {
      try {
        const serializableNote = {
          id: currentNote.value.id,
          title: currentNote.value.title,
          content: currentNote.value.content,
          createdAt: currentNote.value.createdAt.toISOString(),
          updatedAt: currentNote.value.updatedAt.toISOString()
        }

        const result = await window.api.updateDetachedNote(serializableNote)
        if (result.success) {
          console.log('脱出窗口note数据已更新')
        } else {
          console.error('更新脱出窗口note失败:', result.error)
        }
      } catch (error) {
        console.error('更新脱出窗口note时出错:', error)
      }
    }
  }
}

// 删除笔记
const deleteNote = (noteId: number): void => {
  const index = notes.value.findIndex((note) => note.id === noteId)
  if (index !== -1) {
    notes.value.splice(index, 1)
    if (currentNote.value?.id === noteId) {
      currentNote.value = notes.value[0] || null
    }
  }
}

// 脱出窗口置顶功能
const handleToggleDetachedWindowAlwaysOnTop = async (): Promise<void> => {
  if (!window.api || !window.api.toggleDetachedWindowAlwaysOnTop) {
    console.error('脱出窗口置顶API不可用')
    return
  }

  try {
    const result = await window.api.toggleDetachedWindowAlwaysOnTop()
    if (result.success) {
      isDetachedWindowAlwaysOnTop.value = result.isAlwaysOnTop || false
      console.log('脱出窗口置顶状态已切换:', isDetachedWindowAlwaysOnTop.value)
    } else {
      console.error('切换脱出窗口置顶状态失败:', result.error)
    }
  } catch (error) {
    console.error('切换脱出窗口置顶状态时出错:', error)
  }
}

// 获取脱出窗口置顶状态
const getDetachedWindowAlwaysOnTop = async (): Promise<void> => {
  if (!window.api || !window.api.getDetachedWindowAlwaysOnTop) {
    return
  }

  try {
    const result = await window.api.getDetachedWindowAlwaysOnTop()
    if (result.success) {
      isDetachedWindowAlwaysOnTop.value = result.isAlwaysOnTop || false
    }
  } catch (error) {
    console.error('获取脱出窗口置顶状态失败:', error)
  }
}

// 处理脱出窗口置顶状态变化
const handleDetachedWindowAlwaysOnTopChanged = (isAlwaysOnTop: boolean): void => {
  isDetachedWindowAlwaysOnTop.value = isAlwaysOnTop
  console.log('脱出窗口置顶状态已变化:', isAlwaysOnTop)
}

// 检查是否为脱出窗口并初始化
const initializeApp = async (): Promise<void> => {
  try {
    const detachedNote = await window.api.getDetachedNote()
    if (detachedNote) {
      // 脱出窗口模式
      isDetachedMode.value = true
      // 将日期字符串转换为Date对象
      const note: Note = {
        ...detachedNote,
        createdAt: new Date(detachedNote.createdAt),
        updatedAt: new Date(detachedNote.updatedAt)
      }
      currentNote.value = note
      notes.value = [note]

      // 获取初始置顶状态
      await getDetachedWindowAlwaysOnTop()

      // 设置脱出窗口置顶状态监听器
      if (window.api && window.api.onDetachedWindowAlwaysOnTopChanged) {
        window.api.onDetachedWindowAlwaysOnTopChanged(handleDetachedWindowAlwaysOnTopChanged)
        console.log('已设置脱出窗口置顶状态监听器')
      }
    } else {
      // 正常模式，初始化示例笔记
      if (notes.value.length === 0) {
        createNote()
        if (currentNote.value) {
          currentNote.value.title = '欢迎使用 Orange Note'
          currentNote.value.content =
            '# 欢迎使用 Orange Note\n\n这是一个基于 Electron + Vue 的现代化笔记应用。\n\n## 功能特性\n\n- 📝 实时编辑\n- 💾 自动保存\n- 🔍 快速搜索\n- 🎨 简洁界面\n- 🪟 拖拽脱出窗口\n\n开始记录您的想法吧！'
        }
      }

      // 设置note返回事件监听器（仅在主窗口中）
      if (window.api && window.api.onNoteReturned) {
        window.api.onNoteReturned(handleNoteReturned)
        console.log('已设置note返回事件监听器')
      }
    }
  } catch (error) {
    console.error('初始化应用失败:', error)
  }
}

// 处理note脱出请求
const handleDetachNote = async (note: Note): Promise<void> => {
  console.log('开始处理note脱出请求:', note.title)

  // 检查API是否可用
  if (!window.api || !window.api.createDetachedWindow) {
    console.error('window.api 不可用')
    return
  }

  try {
    console.log('调用 createDetachedWindow API')

    // 将Date对象转换为字符串以便序列化
    const serializableNote = {
      id: note.id,
      title: note.title,
      content: note.content,
      createdAt: note.createdAt.toISOString(),
      updatedAt: note.updatedAt.toISOString()
    }

    const result = await window.api.createDetachedWindow(serializableNote)
    console.log('API调用结果:', result)

    if (result.success) {
      console.log('成功创建脱出窗口，删除原note')
      // 成功创建脱出窗口，从主窗口中移除这个note
      deleteNote(note.id)
    } else {
      console.error('创建脱出窗口失败:', result.error)
    }
  } catch (error) {
    console.error('脱出note失败:', error)
  }
}

// 处理note返回
const handleNoteReturned = (serializableNote: {
  id: number
  title: string
  content: string
  createdAt: string
  updatedAt: string
}): void => {
  console.log('收到返回的note:', serializableNote.title)

  // 将序列化的note转换为带Date对象的note
  const returnedNote: Note = {
    id: serializableNote.id,
    title: serializableNote.title,
    content: serializableNote.content,
    createdAt: new Date(serializableNote.createdAt),
    updatedAt: new Date(serializableNote.updatedAt)
  }

  // 检查是否已存在（避免重复添加）
  const existingIndex = notes.value.findIndex((note) => note.id === returnedNote.id)
  if (existingIndex === -1) {
    // 将返回的note添加到列表开头
    notes.value.unshift(returnedNote)
    console.log('note已重新添加到主应用:', returnedNote.title)
  } else {
    console.log('note已存在，不重复添加:', returnedNote.title)
  }
}

onMounted(() => {
  initializeApp()
})

onUnmounted(() => {
  // 清理监听器
  if (window.api && window.api.removeNoteReturnedListener) {
    window.api.removeNoteReturnedListener()
  }
  if (window.api && window.api.removeAlwaysOnTopListener) {
    window.api.removeAlwaysOnTopListener()
  }
  if (window.api && window.api.removeDetachedWindowAlwaysOnTopListener) {
    window.api.removeDetachedWindowAlwaysOnTopListener()
  }
})
</script>

<template>
  <v-app>
    <!-- 脱出窗口模式：只显示编辑器 -->
    <div v-if="isDetachedMode" class="detached-mode">
      <v-app-bar color="grey-lighten-4" flat>
        <v-app-bar-title>
          {{ currentNote?.title || '无标题' }}
        </v-app-bar-title>
        <v-spacer></v-spacer>

        <!-- 置顶按钮 -->
        <v-btn
          :icon="isDetachedWindowAlwaysOnTop ? 'mdi-pin' : 'mdi-pin-outline'"
          :color="isDetachedWindowAlwaysOnTop ? 'primary' : 'grey'"
          size="small"
          variant="text"
          @click="handleToggleDetachedWindowAlwaysOnTop"
        >
          <v-icon :icon="isDetachedWindowAlwaysOnTop ? 'mdi-pin' : 'mdi-pin-outline'"></v-icon>
          <v-tooltip activator="parent" location="bottom">
            {{ isDetachedWindowAlwaysOnTop ? '取消置顶' : '窗口置顶' }}
          </v-tooltip>
        </v-btn>

        <v-chip size="small" color="info" variant="outlined" class="ml-2">
          关闭窗口将返回主应用
        </v-chip>
      </v-app-bar>

      <v-main>
        <NoteEditor :note="currentNote" @update-content="updateNote" />
      </v-main>
    </div>

    <!-- 正常模式：显示完整界面 -->
    <template v-else>
      <!-- 侧边栏 -->
      <v-navigation-drawer permanent width="300" color="grey-darken-4" theme="dark">
        <Sidebar
          :notes="notes"
          :current-note="currentNote"
          @select-note="selectNote"
          @create-note="createNote"
          @delete-note="deleteNote"
          @detach-note="handleDetachNote"
        />
      </v-navigation-drawer>

      <!-- 主内容区域 -->
      <v-main>
        <v-container fluid class="pa-0 fill-height">
          <v-row no-gutters class="fill-height">
            <v-col>
              <Toolbar :current-note="currentNote" @new-note="createNote" />
              <NoteEditor :note="currentNote" @update-content="updateNote" />
            </v-col>
          </v-row>
        </v-container>
      </v-main>
    </template>
  </v-app>
</template>

<style scoped>
.detached-mode {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.fill-height {
  height: 100vh;
}
</style>
